<template>
  <div>
    <!--增加或更新选项-->
    <el-dialog :title=formTitle :visible.sync="flagShowPropertyOptionForm">
      <el-form :model="propertyOptionFormData" label-width="150px" style="text-align:left">
        <el-form-item label="选项名称" required>
          <el-input v-model="propertyOptionFormData.name" placeholder="具体选项名" max-length="30"></el-input>
        </el-form-item>
        <div v-if="propertyList[curPropertyIndex] && propertyList[curPropertyIndex].isMain">
          <el-form-item label="价格(单位: 分)">
            <el-input-number v-model="propertyOptionFormData.price" placeholder="商品价格或额外价格"
                             type="number"></el-input-number>
          </el-form-item>
          <el-form-item label="库存">
            <el-input-number v-model="propertyOptionFormData.count" type="number"></el-input-number>
          </el-form-item>
        </div>
        <el-form-item>
          <el-checkbox v-model="propertyOptionFormData.disabled">禁用
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button @click="flagShowPropertyOptionForm=false">取消</el-button>
          <el-button type="primary" @click="submitPropertyOptionForm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--显示或编辑属性列表-->
    <div style="padding-left: 30px">
      <div v-for="(property,propertyIndex) in propertyList"
           :key="propertyIndex"
           style="margin-bottom: 15px;">
        <div style=" line-height: 40px;">
          <el-input style="width: 150px; margin-right: 30px" size="mini"
                    v-model="property.name" placeholder="属性名称" maxlength="10"/>
          <el-checkbox label="主属性" v-model="property.isMain" @change="setMainProperty(property)"></el-checkbox>
          <el-checkbox label="必选" v-model="property.required" :disabled="property.isMain"></el-checkbox>
          <el-button type="text" style="margin-left: 20px;" @click="propertyList.splice(propertyIndex, 1)">删除
          </el-button>
        </div>
        <div style="display: flex; justify-content: flex-start; width: 700px; flex-wrap: wrap">
          <div v-for="(option,optionIndex) in property.options" :key="optionIndex">
            <el-tag :key="option.name"
                    closable
                    @close="property.options.splice(optionIndex, 1)"
                    @click="toUpdatePropertyOption(propertyIndex, optionIndex, option)"
                    style="margin-right: 10px; white-space: nowrap; overflow:hidden; text-overflow: ellipsis; color: black">
              {{ option.name }}
              <span v-if="property.isMain">
                  ￥{{ option.price >= 0 ? option.price / 100 : 0 }}
                  <span v-if="option.disabled" style="color: red">（已禁用）</span>
                  <span v-else-if="option.count > 0">（库存{{ option.count }}）</span>
                  <span v-else style="color: red">（已售空）</span>
              </span>
              <span v-else-if="option.disabled" style="color: red">（已禁用）</span>
            </el-tag>
          </div>
          <el-button type="text" size="mini" @click="toAddPropertyOption(propertyIndex)">
            +添加选项
          </el-button>
        </div>
      </div>
      <div style="margin-bottom: 10px;">
        <el-input style="width: 150px;" size="mini" v-model="propertyName" placeholder="属性名称" maxlength="10"/>
        <el-button size="mini" type="text" @click="goAddGoodsProperty()" style="margin-left: 10px">
          +添加属性
        </el-button>
      </div>
      <el-button size="mini" @click="propertyList=JSON.parse(JSON.stringify(curGoods.propertyList))">
        取消更新
      </el-button>
      <el-button size="mini" type="primary" @click="submitPropertyListUpdate">
        提交更新
      </el-button>
    </div>
  </div>
</template>
<script>
import * as goodsAdminApi from "../../api/goodsAdminApi";

export default {
  name: "goodsProperty",
  props: {
    curGoods: {
      type: Object,
      default: () => {
        propertyList: []
      }
    },
  },
  data() {
    return {
      // ********** 商品属性 ************ //
      flagShowPropertyOptionForm: false,
      formTitle: "添加属性选项",
      propertyList: [], // 属性列表副本, 编辑用,
      propertyName: '', // 属性名称
      curPropertyIndex: 0,
      curOptionIndex: 0,
      propertyOptionFormData: {}
    }
  },
  mounted() {
    this.propertyList = JSON.parse(JSON.stringify(this.curGoods.propertyList))
  },
  methods: {
    // 添加商品属性
    goAddGoodsProperty() {
      this.propertyName = this.propertyName.trim()
      if (this.propertyName === "") {
        this.$message.error("请输入属性名")
        return
      }
      for (let i = 0; i < this.propertyList.length; i++) {
        if (this.propertyList[i].name === this.propertyName) {
          this.$message.error("属性名已存在: " + this.propertyName)
          return
        }
      }

      this.propertyList.push({
        name: this.propertyName,
        isMain: false,
        required: false,
        options: [],
      })
      this.propertyName = ""
    },
    // 设置主属性
    setMainProperty(property) {
      let setMain = property.isMain
      for (let i = 0; i < this.propertyList.length; i++)
        this.propertyList[i].isMain = false
      if (setMain) {
        property.isMain = true
        property.required = true
      }
      this.propertyList = JSON.parse(JSON.stringify(this.propertyList))
    },
    // 添加属性选项
    toAddPropertyOption(propertyIndex) {
      this.formTitle = '添加属性选项' + propertyIndex
      this.flagShowPropertyOptionForm = true
      this.curPropertyIndex = propertyIndex
      this.propertyOptionFormData = { // 空表单
        name: "",
        price: 0,
        count: 0,
      }
    },
    // 更新属性选项
    toUpdatePropertyOption(propertyIndex, optionIndex, option) {
      this.formTitle = '更新属性选项'
      this.flagShowPropertyOptionForm = true
      this.propertyOptionFormData = JSON.parse(JSON.stringify(option));
      this.curPropertyIndex = propertyIndex
      this.curOptionIndex = optionIndex
    },
    // 添加或更新属性选项
    submitPropertyOptionForm() {
      let name = this.propertyOptionFormData.name
      if (!name) {
        this.$message.error("请填写选项名称")
        return
      }
      if (this.propertyList[this.curPropertyIndex].isMain && this.propertyOptionFormData.price <= 0) {
        this.$message.error("当前属性为主属性，价格必须设置且大于0")
        return
      }

      let options = this.propertyList[this.curPropertyIndex].options
      if (this.formTitle.startsWith('添加')) {
        for (let i = 0; i < options.length; i++)
          if (options[i].name === name) {
            this.$message.error("属性选项重复：" + name)
            return
          }
        this.flagShowPropertyOptionForm = false
        options.push(this.propertyOptionFormData)
      } else if (this.formTitle.startsWith('更新')) {
        this.flagShowPropertyOptionForm = false
        options[this.curOptionIndex] = this.propertyOptionFormData
      }
    },
    // 提交更新属性列表
    submitPropertyListUpdate() {
      let list = this.propertyList
      for (let i = list.length - 1; i >= 0; i--) {
        let options = list[i].options
        if (list[i].isMain) {
          for (let j = 0; j < options.length; j++) {
            if (options[j].price > 0)
              continue
            this.$message.error("主属性的选项的价格必须大于0")
            return
          }
        }
        if (!options || options.length === 0) { // 没有任何选项就直接删除该属性
          list.splice(i, 1)
        }
      }

      goodsAdminApi.updateGoods({
        data: {
          id: this.curGoods.id,
          propertyList: list,
        },
        success: () => {
          this.$emit('updateGoodsPropertyList'); // 通知父组件去刷新curGoods
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
